<?php
/**
 * AJAX Handler for Contrib: Add - Contributors are added to a project here.
 * 
 * I have made sure Libdebug is silent in AJAX. This is because it can intefere with the HTML/Javascript as Libdebug Appends after </html>.
 * If you have a problem and need to debug comment $_LIBDEBUG->silence(); (the framework must also be in debugging mode for this to work)
 */

    $_ECLIPSEMDE = array();
    
    // Disable Templating System
    $_ECLIPSEMDE['TEMPLATING'] = false;
    require_once('../../SiteIncludes.GLOBAL.php');
    
    // Tell libdebug to never print out error information - overrides debugging flags in fwork
    $_LIBDEBUG->silence();
    
    if(EclipseMDE::runningOnMod_Rewrite() === false) {
	// Security Guard, Do Not Let This be accessed by any other means than mod_rewrite
	header("HTTP/1.1 400 Bad Request");
	die($nok_caller);
    }
    
    // Ensure all variables needed are set
    if(isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER !== false && isset($gVAR['alias']) !== false && isset($gVAR['user']) !== false) {
	try {
	    $Project =& $ProjectStash->get($gVAR['alias']);
	    
	    if($Project->userCanEdit($_LOGGEDINUSER->get_userid()) === true) {
		
		$cb_error_msg = false;
		if($gVAR['user'] == $_LOGGEDINUSER->get_userid()) {
		    $cb_error_msg = "That appeared to be you.";
		} else {
		    $ProjectUsers = $Project->getAllMaintainers();
		    if(in_array((int)$gVAR['user'], $ProjectUsers)) {
			if($gVAR['user'] == $Project->getLeadMaintainer()) {
			    $cb_error_msg = "That user is the lead maintainer.";
			} else {
			    $cb_error_msg = "That user is already added.";
			}
		    } else {
			$safe_usr = $sql_conx->real_escape_string($gVAR['user']);
			$query = $sql_conx->query("INSERT INTO `tool_maintainers` ( `pid` , `uid` ) VALUES ( '{$Project->getID()}',  '{$safe_usr}' )");
			if($sql_conx->affected_rows === 0) {
			    $cb_error_msg = "Unknown Error";
			} else {
			    $cb_error_msg = false;
			    $Project->updateWrite($_LOGGEDINUSER->get_userid(), ($Project->userCanAdmin($_LOGGEDINUSER->get_userid(), false) === true ? ProjectEditType::AddMaintainer : ProjectEditType::AdminAddMaintainer), array($safe_usr));
			}
		    }
		}
		echo <<<EOHEAD
			<!DOCTYPE html>
			    <html>
				<head><title></title></head>
				<body>
				    <script type="text/javascript">
EOHEAD;
		    if($cb_error_msg === false) {
			echo <<<MSG
			    parent.UserContribEDJX.addError(false);
			    parent.EDJXConfirmer.show_ok();
MSG;
		    } else {
			echo <<<MSG
			    parent.UserContribEDJX.addError('{$cb_error_msg}');
			    parent.EDJXConfirmer.show_nok();
MSG;
		    }
		    echo <<<EOTAIL
				    </script>
				</body>
			    </html>
		    
EOTAIL;
	    } else {
		throw new InvalidProjectException();
	    }
	} catch(InvalidProjectException $e) {
	    header("HTTP/1.1 400 Bad Request");
	    die($nok_caller);
	}
    } else {
	header("HTTP/1.1 400 Bad Request");
	die($nok_caller);
    }